package com.zhuizikejithreeig.cn.threeigkeji;

import android.app.Application;
import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;


import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.mob.MobSDK;
import com.squareup.leakcanary.LeakCanary;
import com.zhuizikejithreeig.cn.been.IconSaveFile;
import com.zhuizikejithreeig.cn.content.ContectUtils;
import com.zhuizikejithreeig.cn.utils.CrashHandler;
import com.zhuizikejithreeig.cn.utils.ToastMake;
import com.zhuizikejithreeig.cn.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

import static java.lang.System.err;

/**
 * Created by 赵航 on 2018/3/9 0009.
 */

public class CompontApplayCation extends Application {
    public static Context context;
    public static Handler mainHandler;
    public static IconSaveFile driverInfo;
    public static String phone;
    public static String postion="1";
    public static String registCode;
    public static String loginRegistCode;
    public static String loginRegistPhone;
    public static boolean mianToLogin = false;
    public static boolean formLgin = false;
    public static boolean carinfook = false;
    public static boolean loginNeedFinsh = true;


    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new MyAMapLocationListener();
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    private double currentLat;
    private double currentLon;

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        mainHandler = new Handler();
        //网络请求框架
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                //                .addInterceptor(new LoggerInterceptor("TAG"))
                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                .readTimeout(10000L, TimeUnit.MILLISECONDS)
                //其他配置
                .build();
        OkHttpUtils.initClient(okHttpClient);
        //获取全局未捕获的异常
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(getApplicationContext());
        //配置shareSdk
        MobSDK.init(context);
        driverInfo = new IconSaveFile();
        //检测内存泄漏
//        LeakCanary.install(CompontApplayCation.this);


        //添加定位功能
        initLocations();
        //发送位置信息
        sendPosition();
    }

    private void sendPosition() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                //每两分钟发送一次定位
//                                System.out.println("当前坐标的位置是" + currentLat + "============" + currentLon);
                                //获取本地电话号码
                                String phoneNumber = Utils.getString(ContectUtils.PHONESAVE);
                                //网络时间
                                String netTime = getWebsiteDatetime();
                                //本地时间
                                String mLocation = getLocalTime();

                                if (!TextUtils.isEmpty(phoneNumber)) {
                                    //这里上传经纬度,上传本地时间或网络时间,以及电话号码
                                }
                                if (netTime == null) {
                                    //上传本地时间,不管是不是为空,都尽量上传网络时间
                                    netTime = mLocation;
                                }else {
                                    System.out.println("当前坐标的位置是" + currentLat + "============" + currentLon+"电话号码为" + phoneNumber + "网络时间" + netTime + "本地时间" + mLocation);
                                }

                            }
                        }).start();
                        mainHandler.postDelayed(this, 5000);
                    }
                });
            }
        }).start();
    }

    private void initLocations() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(false);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    private class MyAMapLocationListener implements AMapLocationListener {

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {

                    aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    currentLat = aMapLocation.getLatitude();//获取纬度
                    currentLon = aMapLocation.getLongitude();//获取经度
//                    latLonPoint = new LatLonPoint(currentLat, currentLon);  // latlng形式的
//                    /*currentLatLng = new LatLng(currentLat, currentLon);*/   //latlng形式的
//                    Log.i("currentLocation", "currentLat : " + currentLat + " currentLon : " + currentLon);
                    aMapLocation.getAccuracy();//获取精度信息

                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                    System.out.println("定位失败");
                }
            }
        }
    }

    /**
     * 获取指定网站的日期时间
     *
     * @return
     * @author SHANHY
     * @date 2015年11月27日
     */
    private String getWebsiteDatetime() {
        String webUrl = "http://www.ntsc.ac.cn";//中国科学院国家授时中
        try {
            URL url = new URL(webUrl);// 取得资源对象
            URLConnection uc = url.openConnection();// 生成连接对象
            uc.connect();// 发出连接
            long ld = uc.getDate();// 读取网站日期时间
            Date date = new Date(ld);// 转换为标准时间对象
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);// 输出北京时间
            return sdf.format(date);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //获取本地时间
    private String getLocalTime() {

        try {
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            String format = formatter.format(calendar.getTime());

            return format;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}